import Promise from 'promise';
import * as ResultMsg from '../constrants/ResultMsg';
import { SubmenuModel } from '../models';

const fileds = null;

export function find(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  const query = SubmenuModel.find(conditions).select(fileds).setOptions(options);
  return query.exec();
}

export function findOne(appId, conditions, options) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof conditions !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  if (typeof options !== 'object') options = null;
  conditions.appId = appId;
  const query = SubmenuModel.findOne(conditions).select(fileds).setOptions(options);
  return query.exec();
}

export function findOneById(appId, id) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  const query = SubmenuModel.findOne({appId: appId, _id: id });
  return query.exec();
}

export function update(appId, id, data) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof id !== 'string' && typeof id !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof data !== 'object') throw new Error(ResultMsg.NOT_OBJECT);
  const query = SubmenuModel.findByIdAndUpdate(id, { $set: data });
  return query.exec();
}

export function create(appId, parentId, key, value, weight) {
  if (typeof appId !== 'string') throw new Error(ResultMsg.NO_APP_ID);
  if (typeof parentId !== 'string' && typeof parentId !== 'object') throw new Error(ResultMsg.NO_ID);
  if (typeof key !== 'string') throw new Error(ResultMsg.NOT_STRING);
  if (typeof value !== 'string') throw new Error(ResultMsg.NOT_STRING);
  if (typeof weight !== 'number') {
    weight = 0;
  }

  const doc = new SubmenuModel();
  doc.appId = appId;
  doc.parent_id = parentId;
  doc.key = key;
  doc.value = value;
  doc.weight = weight;
  return doc.save();
}
